# Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com>
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause


import os
import sys

from PySide2.QtWidgets import QApplication
from PySide2.QtGui import QDesktopServices
from PySide2.QtNetwork import QHostAddress, QSslSocket
from PySide2.QtCore import (QFile, QFileInfo, QUrl)
from PySide2.QtWebChannel import QWebChannel
from PySide2.QtWebSockets import QWebSocketServer

from standalone.dialog import Dialog
from standalone.core import Core
from standalone.websocketclientwrapper import WebSocketClientWrapper

from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWebEngineWidgets import QWebEnginePage, QWebEngineView, QWebEngineProfile


# 自定义页面类
class MyWebEnginePage(QWebEnginePage):
    def javaScriptConsoleMessage(self, level: QWebEnginePage.JavaScriptConsoleMessageLevel,
                                 message: str, lineNumber: int, sourceID: str):
        # 接收js控制台 打印的信息
        print("接收js数据:", message)
        # 保存的动作
        return super(MyWebEnginePage, self).javaScriptConsoleMessage(level, message, lineNumber, sourceID)


# 自定义web引擎类
class MyWebEngineView(QWebEngineView):
    def __init__(self):
        QWebEngineView.__init__(self)
        self.setPage(MyWebEnginePage(self))


class MyWindow(QWidget):
    def __init__(self, title="laufing"):
        super(MyWindow, self).__init__()
        # 窗口的尺寸及居中
        self.resize(800, 600)
        desk = QDesktopWidget().geometry()
        width, height = desk.width(), desk.height()
        self.move(width // 2 - self.width() // 2, height // 2 - self.height() // 2)

        # 窗口标题
        self.setWindowTitle(title)
        self.setWindowIcon(QIcon("./imgs/dog.jpg"))


    def set_ui(self, sub_win):
        vb = QVBoxLayout(self)
        self.web_view = MyWebEngineView()
        vb.addWidget(self.web_view)
        vb.addWidget(sub_win)

    def set_url(self, url):
        self.web_view.page().load(url)


if __name__ == '__main__':
    import sys

    # 创建应用程序
    app = QApplication(sys.argv)

    win = MyWindow("测试可视化")
    #win.show()

    # 进入消息循环
    #sys.exit(app.exec_())

    #
    if not QSslSocket.supportsSsl():
        print('The example requires SSL support.')
        sys.exit(-1)

    cur_dir = os.path.dirname(os.path.abspath(__file__))
    # js_file_info = QFileInfo(f"{cur_dir}/qwebchannel.js")
    # if not js_file_info.exists():
    #     # 从资源文件中拷贝
    #     QFile.copy(":/qtwebchannel/qwebchannel.js",
    #                js_file_info.absoluteFilePath())

    # setup the QWebSocketServer
    server = QWebSocketServer("QWebChannel Server",
                              QWebSocketServer.NonSecureMode)
    if not server.listen(QHostAddress.LocalHost, 12345):
        print("Failed to open web socket server.")
        sys.exit(-1)

    # wrap WebSocket clients in QWebChannelAbstractTransport objects
    client_wrapper = WebSocketClientWrapper(server)

    # setup the channel
    channel = QWebChannel()
    client_wrapper.client_connected.connect(channel.connectTo)

    # setup the UI
    dialog = Dialog()

    # setup the core and publish it to the QWebChannel
    core = Core(dialog)
    channel.registerObject("core", core)
    win.set_ui(dialog)

    # open a browser window with the client HTML page
    # url = QUrl.fromLocalFile(f"{cur_dir}/index.html")
    url = QUrl("http://localhost:5050/chart/add")
    # QDesktopServices.openUrl(url) # 浏览器中打开
    win.set_url(url)
    # display_url = url.toDisplayString()
    # message = f"Initialization complete, opening browser at {display_url}."
    # dialog.display_message(message)
    win.show()


    sys.exit(app.exec_())
